<template>
  <Nav_bar :title="'设备详情'" />
  <div class="device_details_box">
    <!-- 设备信息 -->
    <div class="details_info_box">
      <div class="device_name">{{ machineInfoStore.machineInfo?.machineName }}</div>
      <div class="device_id">
        设备编号:
        <span class="_id">{{ machineInfoStore.machineInfo?.machineId }}</span>
      </div>
      <div class="service_status">
        客服状态:
        <span class="_service">{{ replacementStatus === 1 ? '在线' : '不在线' }}</span>
      </div>
      <div class="device_place">
        地点:
        <span class="_place">{{ machineInfoStore.machineInfo?.positionAddr }}</span>
      </div>
      <div class="device_status">
        状态:
        <span class="_status">{{
          machineInfoStore.machineInfo?.operationStatus === 1
            ? '营业中'
            : machineInfoStore.machineInfo?.operationStatus === 2
              ? '休息中'
              : machineInfoStore.machineInfo?.operationStatus === 3
                ? '故障中'
                : ''
        }}</span>
      </div>
      <div class="replenishment_button" @click.stop="skip_replenishment()">补货</div>
    </div>
    <!-- 设备制作情况 -->
    <div class="details_make_box">
      <div class="details_make_top">
        <div class="make_top_search">
          <input
            class="_input"
            v-model.trim="tail_number"
            type="text"
            maxlength="4"
            placeholder="请输入4位手机尾号"
          />
          <van-icon name="search" @click.stop="getMachineOrderList()" color="#04D394" size="14px" />
        </div>
        <button type="button" class="one_make" :disisabled="isDisisabled" @click.stop="oneMake()">
          一键恢复
        </button>
      </div>
      <!-- 表格列表 -->
      <div class="table_box">
        <div class="table_head">
          <span class="_item" v-for="item in table_head_list" :key="item.head_name">
            {{ item.head_name }}
          </span>
        </div>
        <!-- 表格循环主体 -->
        <div class="table_list" v-if="table_bodyList?.length">
          <van-pull-refresh
            style="width: 100%; height: 100%"
            v-model="refreshLoading"
            @refresh="onRefresh"
          >
            <div
              class="table_item"
              @click.stop="skip_details(item.orderSn)"
              :class="changeIntStatus(item.intStatus)"
              v-for="(item, index) in table_bodyList"
              :key="index"
            >
              <span class="_name">{{ item.comboName }}</span>
              <span class="tail_number">{{
                item.orderType === 0 ? item.userMobile : item.checkCode
              }}</span>
              <span class="order_time">{{ item.orderTime }}</span>
              <span class="queueing_time">{{ item.queueTime ? item.queueTime : '' }}</span>
              <span class="_status">{{
                item.intStatus === 1
                  ? '是'
                  : item.intStatus === 8
                    ? ''
                    : item.intStatus === 9
                      ? ''
                      : '否'
              }}</span>
              <span class="_switch">
                <van-switch
                  v-if="item.intStatus === 1 || item.intStatus === 2 || item.intStatus === 4"
                  :disabled="item.intStatus !== 4 ? true : false"
                  v-model="item.makeStatus"
                  :active-color="item.intStatus === 4 ? '#B50000' : '#09D336'"
                  :inactive-color="
                    item.intStatus === 4 ? '#B50000' : item.intStatus === 2 ? '#999999' : '#E9E9E9'
                  "
                  :size="10"
                  @click.stop="changeSwitch(item)"
                />
              </span>
            </div>
          </van-pull-refresh>
        </div>
        <div class="vacancy_make_list" v-else>
          <img src="/src/assets/images/vacancy_make_list.png" alt="" />
          <div>暂无数据</div>
        </div>
      </div>
    </div>
  </div>
  <Tabbar />
</template>

<script setup>
import { ref, reactive, onMounted, watch, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getMachineInfoApi, getMachineOrderListApi, postOrderMakeApi } from '@/api/machine/machine'
import { useMachineInfoStore } from '@/stores'
import { Msg } from '@/utils/tools'

const machineInfoStore = useMachineInfoStore()
// const $route = useRoute()
const $router = useRouter()
const tail_number = ref()
const refreshLoading = ref(false)
const table_head_list = [
  { head_name: '名称' },
  { head_name: '手机尾号' },
  { head_name: '下单时间' },
  { head_name: '排队时间' },
  { head_name: '状态' },
  { head_name: '制作' },
]
const table_bodyList = ref([])
const replacementStatus = ref()
const isDisisabled = ref(false)
const selectList = ref([])
let isInterval = true // 是否进入轮询的判断值
//
/**获取设备基本信息 */
const getMachineInfo = async () => {
  const res = await getMachineInfoApi({ machineId: machineInfoStore.machineInfo?.machineId })
  // console.log(res)
  replacementStatus.value = res?.data.replacementStatus
  machineInfoStore.machineInfo['positionName'] = res?.data?.positionName
  machineInfoStore.machineInfo['machineType'] = res?.data?.machineType

  console.log(machineInfoStore.machineInfo)
}

/**获取设备的所有套餐排队信息 ,并且增加长轮询 */
const getMachineOrderList = async () => {
  try {
    const res = await getMachineOrderListApi({
      machineId: machineInfoStore.machineInfo?.machineId,
      phone: tail_number.value,
    })
    table_bodyList.value = res.data.map((item) => {
      // 根据itme 状态，添加一个新的key进去
      return {
        ...item,
        makeStatus: item.status === 'InTheMaking' ? true : false,
      }
    })
    console.log(table_bodyList.value)
  } catch (error) {}
}
// 设置长轮询，每隔一段时间更新一次订单列表
const interval = setInterval(async () => {
  await getMachineOrderList()
}, 5000) //
// 页面卸载的时候关闭定时器
onBeforeUnmount(() => {
  clearInterval(interval)
})

// 监听 tail_number的长度，进行触发方法
watch(
  () => tail_number.value,
  (newVal) => {
    if (newVal.length === 0 || newVal.length === 4) {
      getMachineOrderList()
    }
  },
)

/**
 * * 跳转到订单的详情页
 * @param orderId 订单id
 */
const skip_details = (orderId) => {
  $router.push({ path: '/order_details', query: { orderId } })
}
/**
 * * 跳转到补货页
 */
const skip_replenishment = () => {
  $router.push({
    path: '/replenishment',
    query: { machineType: machineInfoStore.machineInfo['machineType'] },
  })
}
/**一键恢复 */
const oneMake = async () => {
  if (!selectList.value.length) return Msg('请选中需要恢复的排队套餐')
  isDisisabled.value = true
  const paramList = selectList.value.map((item) => {
    return {
      orderId: item.orderSn,
      orderDetailId: item.orderDetailId,
    }
  })
  const res = await postOrderMakeApi(paramList).finally(() => {
    isDisisabled.value = false
    selectList.value = []
  })
  res.code === 200 ? getMachineOrderList() : null
}
/** 点击制作开关 */
const changeSwitch = (e) => {
  if (!e.makeStatus) return
  isInterval = false // 暂停轮询
  selectList.value.push(e)
}

/**触发下拉刷新 */
const onRefresh = () => {
  selectList.value = []
  getMachineOrderList().finally(() => {
    refreshLoading.value = false
  })
}

/**
 * * 返回css匹配的 class
 * @param 1  正在制作 —— return 'InTheMaking'
 * @param 2 排队生产 —— return 'QueueProduction'
 * @param 3 已支付未生产 —— return 'PaidButNotProduced'
 * @param 4 出餐异常 —— return 'MakeExceptions'
 * @param 5 等待付款 —— return 'WaitForPayment'
 * @param 6 取消订单 —— return 'CancelAnOrder'
 * @param 7 已退款 —— return 'CancelAnOrder'
 * @param 8 已完成  —— return '_completed'
 * @param 9 已取餐 —— return '_completed'
 */
const changeIntStatus = (intStatus) => {
  if (intStatus === 1) {
    return 'InTheMaking' // 正在制作
  } else if (intStatus === 2) {
    return 'QueueProduction' // 排队生产
  } else if (intStatus === 3) {
    return 'PaidButNotProduced' // 已支付未生产
  } else if (intStatus === 4) {
    return 'MakeExceptions' // 出餐异常
  } else if (intStatus === 5) {
    return 'WaitForPayment' // 等待付款
  } else if (intStatus === 6) {
    return 'CancelAnOrder' // 取消订单
  } else if (intStatus === 7) {
    return 'CancelAnOrder' //  已退款
  } else if (intStatus === 8) {
    return '_completed' // 已完成
  } else if (intStatus === 9) {
    return '_completed' // 已取餐
  }
}

onMounted(() => {
  getMachineInfo()
  getMachineOrderList()
})
</script>

<style lang="scss" scoped>
.van-nav-bar {
  height: 44px;
  line-height: 44px;
  padding: 0 9px 0 5px;
  background-color: #5ed1ae;
  .van-nav-bar__content {
    height: 44px;
    line-height: 44px;
    .van-nav-bar__title {
      color: #fff;
      font-weight: 400;
      font-size: var(--fs18);
    }
  }
}

.device_details_box {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  min-height: calc(100% - 44px);
  background-color: var(--defaultBgc);
  padding: 14px 0 102px 0;
  .details_info_box,
  .details_make_box {
    width: 347px;
    border-radius: 4px;
    background: #fff;
    box-shadow: 0px 4px 4px 0px rgba(0, 0, 0, 0.08);
  }
}
.details_info_box {
  position: relative;
  padding: 8px;
  font-size: 12px;
  color: #333;
  margin-bottom: 7px;
  .device_name {
    font-size: 14px;
  }
  .device_id,
  .service_status,
  .device_place,
  .device_status {
    margin-top: 7px;
  }
  ._id,
  ._service,
  ._place,
  ._status {
    color: #999;
  }
  .replenishment_button {
    position: absolute;
    right: 12px;
    top: 8px;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 45px;
    height: 20px;
    line-height: 20px;
    border-radius: 3px;
    border: 1px solid #5fcfae;
    color: var(--subjectFc);
    font-size: var(--fs12);
  }
}

.details_make_box {
  height: 454px;
  padding-top: 8px;
  .details_make_top {
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 0 10px 0 7px;
    margin-bottom: 10px;
    .one_make {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 59px;
      height: 20px;
      border-radius: 3px;
      border: 1px solid #15d39c;
      font-size: 12px;
      color: #00b681;
      background-color: transparent;
    }
    .make_top_search {
      display: flex;
      align-items: center;
      min-width: 160px;
      height: 20px;
      border-radius: 3px;
      background: rgba(19, 217, 158, 0.24);
      padding: 0 3px 0 6px;
      font-size: 12px;
      ._input {
        color: #08c48c;
        background-color: transparent;
        &::placeholder {
          color: #08c48c; /* 设置为你想要的颜色 */
        }
      }
    }
  }
}
.table_box {
  width: 100%;
  padding-bottom: 100px;
}
.table_head {
  width: 100%;
  height: 33px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 5px 5px 0px 0px;
  background: #ebfff9;
  font-size: 12px;
  color: #009468;
  padding: 0 9px;
  ._item:nth-child(1) {
    width: 72px;
    text-align: center;
  }
}
.table_list {
  width: 100%;
  min-height: 350px;
  background-color: #fff;
  :deep(.van-pull-refresh__track) {
    min-height: 350px;
  }
  .table_item {
    width: 100%;
    height: 29px;
    line-height: 29px;
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    padding: 0 9px;
    ._name {
      width: 72px;
      text-align: center;
      overflow: hidden; /* 溢出隐藏 */
      text-overflow: ellipsis; /* 文字溢出省略 */
      white-space: nowrap; /* 防止文本换行 */
    }
    .tail_number,
    .order_time,
    .queueing_time {
      width: 48px;
      text-align: center;
      color: #999999;
    }
    ._status {
      width: 24px;
      text-align: center;
    }
    ._switch {
      width: 24px;
      display: flex;
      justify-content: end;
      align-items: center;
    }
  }
  .InTheMaking {
    color: #09d336;
    .tail_number,
    .order_time,
    .queueing_time {
      color: #09d336;
    }
  }
  .QueueProduction {
    color: #ff974c;
    .tail_number,
    .order_time,
    .queueing_time {
      color: #ff974c;
    }
  }
  .MakeExceptions {
    color: #b50000;
    .tail_number,
    .order_time,
    .queueing_time {
      color: #b50000;
    }
  }
  .CancelAnOrder {
    position: relative;
    color: #999;
    .tail_number,
    .order_time,
    .queueing_time {
      color: #999;
    }
  }
  .CancelAnOrder::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    border-top: 1px solid black;
  }
  ._completed {
    color: #999;
    .tail_number,
    .order_time,
    .queueing_time {
      color: #999;
    }
  }
  .PaidButNotProduced {
    color: #333;
    .tail_number,
    .order_time,
    .queueing_time {
      color: #333;
    }
  }
}

.vacancy_make_list {
  width: 100%;
  height: 454px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  img {
    width: 136px;
    height: 98px;
  }
  div {
    margin-top: 18px;
    font-size: 14px;
  }
}
</style>
